import React, { Component } from 'react';
import { base, getBusinessInfo, ajax, toast ,getMultiLang} from 'nc-lightapp-front';
const { NCButton: Button, NCSelect: Select, NCModal: Modal } = base;

import { RadioItem, SelectItem } from '../../FormItems';
import AssidModal from '../../getAssDatas2';
import ReferLoader from '../../../ReferLoader/index.js';
import { accountRefCode } from '../../../ReferLoader/constants.js';
import {accbookRefcode} from '../../../ReferLoader/constants';
import './index.less';
/**
 * 公式弹框
 * pk_accountingbook,
 * pk_org
 * paramType： 标题title，
 * handleFormulaParamOK  
 * visible
 */
export default class FormulaParam extends Component {
	constructor(props) {
		super(props);
		this.state = {
			json:{},
			appcode: this.props.appcode,
			paramType: this.props.paramType,
			listItem: {
				// accountcode: { display: '', value: '' },
				pk_accountingbook:{display: '', value: ''},// 跨账簿，核算账簿pk
				accountcode: { refcode: [], refpk: [] },
				year: { display: '', value: '' },
				period: { display: '', value: '' },
				direction: { display: '', value: '' },
				ceDirection: { display: '', value: 'default' }
			},
			accountcode: [],
			formulaData: '',
			yearList: [],
			selectedYear: '',
			periodList: [],
			accountBooks:[],
			bookCode:'' // 跨账簿，核算账簿code
		};
	}
	// 获取辅助核算值
	getAssData() {
		return this.refs.assidmodal.exportAssData();
	}
	getInitListItem = () => {
		return {
			accountcode: { refcode: [], refpk: [] },
			year: { display: '', value: '' },
			period: { display: '', value: '' },
			direction: { display: '', value: '' },
			pk_accountingbook:{display: '', value: ''},
			ceDirection: { display: '', value: 'default' }
		}
	}
	// 获取会计年列表
	getYears = (pk_accountingbook) => {
		let self = this;
		// let {pk_accountingbook}=self.props
		let url = '/nccloud/gl/voucher/yearcombo.do';
		let data = {
			pk_accountingbook: pk_accountingbook
		};

		ajax({
			loading: true,
			url,
			data,
			success: function(res) {
				const { data, error, success } = res;
				if (success) {
					data.unshift('');
					self.setState({
						yearList: data
					});
				} else {
					toast({ content: error.message, color: 'warning' });
					self.setState({
						isLoading: false
					});
				}
			},
			error: function(res) {
				toast({ content: res.message, color: 'warning' });
			}
		});
	};
	// 获取会计期间列表
	getPeriod = (checkyear) => {
		let self = this;
		let { pk_accountingbook } = this.props;
		let url = '/nccloud/gl/voucher/periodcombo.do';
		let data = {
			pk_accountingbook: pk_accountingbook,
			year: checkyear
		};
		ajax({
			loading: true,
			url,
			data,
			success: function(res) {
				const { data, error, success } = res;
				if (success) {
					data.unshift('');
					self.setState({
						periodList: data
					});
				} else {
					toast({ content: error.message, color: 'warning' });
				}
			},
			error: function(res) {
				toast({ content: res.message, color: 'warning' });
			}
		});
	};
	// 改变会计年
	handleYearChange(value) {
		let { listItem } = this.state;
		listItem.year.value = value;
		listItem.period.value = '';
		this.setState(
			{
				listItem,
				periodList: []
			},
			() => {
				this.getPeriod(value);
			}
		);
	}
	// 改变会计期间
	handlePeriodChange(value) {
		let { listItem } = this.state;
		listItem.period.value = value;
		this.setState({
			listItem
		});
	}
	
	// 生成公式
	getgenFormula(funCode, orgData) {
		let url = '/nccloud/gl/glpub/genFormula.do';
		let self = this;
		let sendData;
		if (funCode !== 'CE') {
			let accounts = orgData.accountcode.refcode.toString();
			let assvo = orgData.assvo;
			let tempAss = [];
			if (assvo.length > 0) {
				assvo.map((item) => {
					tempAss.push({
						checktypename: item.checktypename,
						checkvaluename: item.checkvaluename ? item.checkvaluename : '',
						checkvaluecode: item.checkvaluecode ? item.checkvaluecode : ''
					});
				});
			}
			sendData = {
				funCode: orgData.funCode,
				accounts: accounts, //英文逗号分隔
				year: orgData.year,
				period: orgData.period,
				assVOs: tempAss,
				direction: orgData.direction
			};
		} else {
			sendData = {
				funCode: orgData.funCode,
				ceDirection: orgData.ceDirection
			};
		}
		ajax({
			url,
			data: sendData,
			success: function(res) {
				// 默认取科目版本列表最后一个
				const { data, error, success } = res;
				let newData = data;//拼接新的公式,放到最后面，不影响系统的公式
				if(self.props.bookVisible){
					let index = data.indexOf('")')+1;
					if(self.state.bookCode){						
						newData = data.substring(0,index)+',"'+self.state.bookCode+'"'+data.substring(index,data.length);						
					}else{
						newData = data.substring(0,index)+',""'+data.substring(index,data.length);
					}
				}
				if (success) {
					if (newData) {
						self.setState(
							{
								formulaData: newData,
								accountcode: []
							},
							() => {
								self.props.handleFormulaParamOK(self.state);
							}
						);
					}
				} else {
					toast({ content: error.message, color: 'warning' });
				}
			},
			error: function(res) {
				toast({ content: res.message, color: 'warning' });
			}
		});
	}

	// 确定
	handleFormulaParamOK(funCode) {
		let { handleFormulaParamOK } = this.props;
		let { listItem } = this.state;

		let baseData, newData;
		if (funCode === 'CE') {
			baseData = {
				ceDirection: ''
			};
		} else {
			baseData = {
				year: '',
				period: '',
				accountcode: '',
				direction: ''
			};
		}
		for (const key in baseData) {
			if (baseData.hasOwnProperty(key)) {
				baseData[key] = listItem[key].value;
				if (key === 'accountcode') {
					baseData[key] = listItem[key];
				}
			}
		}
		baseData.funCode = funCode;
		if (funCode) {
			if (funCode !== 'CE') {
				let assData = this.refs.assidmodal.exportAssData();
				baseData.assvo = assData;
				newData = baseData;
				// this.getgenFormula(baseData)
				// newData = Object.assign(baseData,assData)
			} else {
				newData = baseData;
			}
		}
		this.getgenFormula(funCode, newData);
	}
	// 取消
	handleCancel() {
		let { handleCancel } = this.props;
		let initListItem = this.getInitListItem()
		if (handleCancel) {
			handleCancel();
			this.setState({
				listItem: initListItem,
				accountcode: []			
			})
		}
	}
	componentWillMount() {
		let { pk_accountingbook } = this.props;
		let callback= (json) =>{
			if (pk_accountingbook) {
				this.getYears(pk_accountingbook);
			} else {
				toast({ content: json['publiccomponents-000071'], color: 'warning' });/* 国际化处理： 未选择核算账簿*/
				return;
			}
            this.setState({
              json:json
               // columns_reportSum:this.columns_reportSum,
				},()=>{
				//initTemplate.call(this, this.props);
            })
        }
		getMultiLang({moduleId:'publiccomponents',domainName:'gl',currentLocale:'simpchn',callback});
	}

	// 辅助核算弹框
	renderAssidModal(prepareddate) {
		let { pk_accountingbook, pk_org } = this.props;
		let { accountcode } = this.state;
		let pk_accasoas = accountcode.map((item) => item.pk_accasoa);
		let assidCondition = {
			pk_accountingbook: pk_accountingbook,
			pk_accasoa: pk_accasoas[0],
			prepareddate: prepareddate, //业务日期
			pk_org: pk_org, //财务组织
			assData: [],
			assid: '',
			checkboxShow: true
		};
		return (
			<AssidModal
				ref="assidmodal"
				refMultiSelect={false}
				showDisableData={true}
				pretentAssData={assidCondition}
				checkboxShow={false}
				includeSubAss = {true}
				checkedAll = {true}
			/>
		);
	}

	// 会计科目参照
	renderReferLoader(listItem) {
		let businessInfo = getBusinessInfo();
		let itemKey = 'accountcode';
		let businessDate = businessInfo.businessDate;

		let { accountcode } = this.state;
		return (
			<div className="paramform_con_row_item width_2" fieldid='accountcode'>
				<span className="lable_name nc-theme-common-font-c">{this.state.json['publiccomponents-000077']}:</span>{/* 国际化处理： 会计科目*/}
				<div className="width_210">
					<ReferLoader
						tag="test"
						fieldid='accountcode_pk'
						refcode={accountRefCode}
						value={accountcode}
						isAccountRefer={true}
						isMultiSelectedEnabled={true}
						isShowDisabledData={true}
						queryCondition={() => {							
							let pk_accountingbook = this.props.pk_accountingbook;
							//跨账簿函数公式，并且选择了账簿
							let kzp_book = listItem.pk_accountingbook.value;
							if(this.props.bookVisible && kzp_book
								&& kzp_book != null 
								&& kzp_book != "")
							{
								pk_accountingbook =	kzp_book;
							} 
							return {
								// 'TreeRefActionExt': "nccloud.web.gl.ref.FilterInOrDecreaseAccSqlBuilder",
								pk_accountingbook: pk_accountingbook,
								dateStr: businessDate.split(' ')[0],
								isDataPowerEnable: 'Y',
								DataPowerOperationCode: 'fi'
							};
						}}
						onChange={(v) => {
							accountcode = v;
							let code_accountcode = v.map((item) => item.refcode);
							let pk_accountcode = v.map((item) => item.refpk);
							listItem.accountcode.refcode = code_accountcode;
							listItem.accountcode.refpk = pk_accountcode;
							this.setState({
								listItem,
								accountcode
							});
						}}
					/>
				</div>
			</div>
		);
	}

	// 财务核算账簿(参考：renderReferLoader，会计科目参照)
	renderReferLoaderBook(listItem) {
		// let businessInfo = getBusinessInfo();
		let itemKey = 'accountbooks';
		let ac = this.props.appcode;
		let { accountbooks } = this.state;
		return (
			<div className="paramform_con_row_item width_2" fieldid='accountcode'>
				<span className="lable_name nc-theme-common-font-c">核算账簿：</span>
				<div className="width_210">
					<ReferLoader
						tag="test"
						fieldid='accountbooks'
						value={accountbooks}
						refcode={accbookRefcode} //参照code
						isMultiSelectedEnabled={false} //是否多选
						showGroup={false}
						isAccountRefer={true}
						showInCludeChildren={true}
						disabledDataShow = {true}
						queryCondition={() => {
							return {
								TreeRefActionExt: "nccloud.web.gl.ref.AccountBookRefSqlBuilder",
								appcode:ac,
								isDataPowerEnable: 'Y',
								DataPowerOperationCode: 'fi'
							};
						}}
						onChange={(v) => {
							accountbooks = v;
							let bookCode = v.refcode;
							listItem.pk_accountingbook.value = v.pk_accountingbook;
							this.setState({ 
								listItem,
								accountbooks,
								bookCode 
							});
						}}
					/>
				</div>
			</div>
		);
	}
	
	renderOption(list) {
		if (list) {
			return list.map((item) => {
				return (
					<Option value={item} key={item}>
						{item}
					</Option>
				);
			});
		} else {
			return <Option value="" key="" />;
		}
	}
	// 会计年
	renderYearSelect() {
		let { yearList } = this.state;
		return (
			<div className="paramform_con_row_item width_2">
				<span className="lable_name nc-theme-common-font-c">{this.state.json['publiccomponents-000078']}:</span>{/* 国际化处理： 会计年度*/}
				<div className="width_210">
					<Select
						// defaultValue={yearList[0]}
						fieldid='accountyear'
						onChange={this.handleYearChange.bind(this)}
					>
						{this.renderOption(yearList)}
						{/* {yearList.map((item, index) => {
							return <Option value={item} key={item} >{item}</Option>
						} )} */}
					</Select>
				</div>
			</div>
		);
	}
	
	// 会计期间
	renderPeriodSelect(listItem, item) {
		let { periodList } = this.state;
		return (
			<div className="paramform_con_row_item width_2">
				<span className="lable_name nc-theme-common-font-c">{this.state.json['publiccomponents-000079']}:</span>{/* 国际化处理： 会计期间*/}
				<div className="width_210">
					<Select fieldid='yearperiod' onChange={this.handlePeriodChange.bind(this)}>
						{this.renderOption(periodList)}
						{/* {periodList?periodList.map((item, index) => {
							return <Option value={item} key={item} >{item}</Option>
						}):<Option value='' key=''>{}</Option>} */}
					</Select>
				</div>
			</div>
		);
	}
	// 方向
	renderSelect(listItem) {
		let itemKey = 'direction';
		let itemChild = [ { value: '', label: '' }, { value: this.state.json['publiccomponents-000072'], label: this.state.json['publiccomponents-000072'] }, { value: this.state.json['publiccomponents-000073'], label: this.state.json['publiccomponents-000073'] } ];/* 国际化处理： 借,借,贷,贷*/
		let defaultVal = this.state.listItem[itemKey].value;
		return (
			<div className="paramform_con_row_item width_2">
				<span className="lable_name nc-theme-common-font-c">{this.state.json['publiccomponents-000080']}:</span>{/* 国际化处理： 方向*/}
				<div className="width_210">
					<SelectItem
						name="direction"
						fieldid='direction'
						defaultValue={defaultVal}
						items={() => {
							return itemChild;
						}}
						onChange={(v) => {
							listItem[itemKey].value = v;
							this.setState({
								listItem
							});
						}}
					/>
				</div>
			</div>
		);
	}
	// CE 单选
	renderRadio(listItem) {
		let itemKey = 'ceDirection';
		let itemChild = [
			{ value: 'default', label: this.state.json['publiccomponents-000074'] },/* 国际化处理： 默认*/
			{ value: 'caclup', label: this.state.json['publiccomponents-000075'] },/* 国际化处理： 向上计算*/
			{ value: 'cacldown', label: this.state.json['publiccomponents-000076'] }/* 国际化处理： 向下计算*/
		];
		return (
			<div className="paramform_con_row_item width_1">
				<span className="lable_name nc-theme-common-font-c">{this.state.json['publiccomponents-000081']}:</span>{/* 国际化处理： 计算方式*/}
				<div className="">
					<RadioItem
						name={itemKey}
						type="customer"
						defaultValue={listItem[itemKey].value ? listItem[itemKey].value : 'default'}
						items={() => {
							return itemChild;
						}}
						onChange={(v) => {
							listItem[itemKey].value = v;
							this.setState({
								listItem
							});
						}}
					/>
				</div>
			</div>
		);
	}

	renderForm(funCode, listItem) {
		let bookVisible = !this.props.bookVisible;
		return (
			<div className="paramform">
				{funCode === 'CE' ? (
					<div className="paramform_con_row">{this.renderRadio(listItem)}</div>
				) : (
					<div className="paramform_con">
						<div className="paramform_con_row" hidden={bookVisible}>
							{this.renderReferLoaderBook(listItem)}
						</div>
						<div className="paramform_con_row">
							{this.renderReferLoader(listItem)}
							{this.renderYearSelect(listItem)}  
						</div>
						<div className='paramform_con_row' >							
							{this.renderSelect(listItem)}
							{this.renderPeriodSelect(listItem)}
						</div>
					</div>
				)}
			</div>
		);
	}

	render() {
		let { visible, paramType } = this.props;
		let { listItem } = this.state;
		let funCode = paramType.funCode;
		let businessInfo = getBusinessInfo();
		let businessDate = businessInfo.businessDate;
		let prepareddate = businessDate.split(' ')[0];
		return (
			<div className="parammodal">
				<Modal fieldid='formulaparam' show={visible} backdrop={false} onHide={this.handleCancel.bind(this)}>
					<Modal.Header closeButton>
						<Modal.Title>{paramType.display}{this.state.json['publiccomponents-000082']}</Modal.Title>{/* 国际化处理： 参数*/}
					</Modal.Header>
					<Modal.Body>
						{this.renderForm(funCode, listItem)}

						{funCode === 'CE' ? '' : this.renderAssidModal(prepareddate)}
					</Modal.Body>
					<Modal.Footer>
						<Button className="button-primary" fieldid='confirm' onClick={this.handleFormulaParamOK.bind(this, funCode)}>
							{this.state.json['publiccomponents-000009']}{/* 国际化处理： 确定*/}
						</Button>
						<Button fieldid='cancel' onClick={this.handleCancel.bind(this)}>{this.state.json['publiccomponents-000010']}</Button>{/* 国际化处理： 取消*/}
					</Modal.Footer>
				</Modal>
			</div>
		);
	}
}
